package com.heima.xxljob.job;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class JobService {

    /**
     * 1、简单任务示例（Bean模式）
     */
    @XxlJob("demo")
    public void demoJobHandler() throws Exception {
        log.info("job invoked.....");
    }

    @XxlJob("sharding")
    public void demosharding(){
        //1. 构建10000个任务
        List<Integer> list = getList();

        //2. 获取总的分配数量和当前任务的的分分片
        int total = XxlJobHelper.getShardTotal();
        int shardIndex = XxlJobHelper.getShardIndex();

        //3. 根据取余算法进行任务的分片
        for (Integer num : list) {
            if(num % total == shardIndex){
                System.out.println(num);
            }
        }
    }

    public List<Integer> getList(){
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            list.add(i);
        }
        return list;
    }
}
